<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-form :model="form" ref="form" label-width="120px" :inline="false" :show-message="false">
      <el-form-item label="疾病诊断编码" prop="diseaseCode">
        <el-input
          v-model.trim="form.diseaseCode"
          placeholder="请输入疾病诊断编码"
        ></el-input>
      </el-form-item>
      <el-form-item label="疾病诊断名称" prop="diseaseName" required>
        <el-input
          v-model.trim="form.diseaseName"
          placeholder="请输入疾病诊断名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="诊断首字母" prop="diseasePinyin">
        <el-input
          v-model.trim="form.diseasePinyin"
          placeholder="请输入诊断首字母"
          @blur="pinyinToggle"
        ></el-input>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" :loading="confirmLoading" @click="confirm"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { addDisease, editDisease } from "@/api/saas/disease";
import { titleToggle } from "@/utils/index";
import pinyin from "js-pinyin";

export default {
  data() {
    return {
      title: '新增诊断结果',
      visible: false,
      confirmLoading: false,
      form: {},
    };
  },
  methods: {
    show(row) {
      Object.assign(this.$data, this.$options.data());
      this.title = row.id ? '编辑诊断结果' : '新增诊断结果',
      this.form = {
        id: row.id || undefined,
        diseaseCode: row.diseaseCode || "",
        diseaseName: row.diseaseName || "",
        diseasePinyin: row.diseasePinyin || "",
      };
      this.visible = true;

      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    pinyinToggle() {
      this.form.diseasePinyin = titleToggle(this.form.diseasePinyin);
    },
    confirm() {
      const that = this;
      that.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            that.confirmLoading = true;
            if(!that.form.diseasePinyin){ // 未填写诊断首字母,自动生成
              let str = pinyin.getCamelChars(that.form.diseaseName);
              that.form.diseasePinyin = titleToggle(str);
            }
            that.form.id
              ? await editDisease(that.form)
              : await addDisease(that.form);
            that.$emit("refresh");
            that.$message.success(that.form.id ? "编辑成功" : "新增成功");
            that.confirmLoading = false;
            that.visible = false;
          } catch (err) {
            that.confirmLoading = false;
          }
        }
      });
    },
  },
};
</script>
